<template>
  <view class="page-container">
    <view class="image-body" v-if="detailImage && detailImage.length > 0">
      <view class="image-big">
        <image
          :src="completeImgPath(activeDetailImage)"
          style="height: 100%; width: 100%"
          mode="aspectFit"
          @click="previewImage(completeImgPath(activeDetailImage))" />
        <text class="count">
          {{ activeDetailIndex }}/{{ detailImage.length }}
        </text>
      </view>
      <view class="image-small-body">
        <view class="image-small">
          <view
            class="image-small-item"
            v-for="(item, index) in detailImage"
            :class="item == activeDetailImage ? 'active' : ''"
            @click="handleSelectImage(index)"
            :key="index">
            <image class="image-body" :src="completeImgPath(item)" />
          </view>
        </view>
      </view>
      <view class="line"></view>
    </view>
    <view v-else class="no-image-data">暂无数据</view>
    <view class="detail-middle">
      <view class="top">
        <view class="name">
          {{ productData?.name }}
        </view>
        <view class="status">
          <uni-tag
            :type="productData?.status == 'on_sale' ? 'success' : 'error'"
            :text="productData?.statusName"></uni-tag>
        </view>
        <view>
          <uni-tag type="primary" :text="productData?.categoryName"></uni-tag>
        </view>
      </view>
      <view class="middle">
        <text class="sellingPrice">￥{{ productData?.sellingPrice }}</text>
        <!-- <text class="originalPrice">￥{{ productData?.originalPrice }}</text> -->
      </view>
    </view>
    <view class="line"></view>
    <!-- 标签容器 -->
    <view class="tab-wrapper">
      <view class="tab-container">
        <view
          v-for="(tab, index) in tabList"
          :key="index"
          class="tab"
          :class="{ active: activeTab.value == tab.value }"
          @click="switchTab(tab)">
          {{ tab.text }}
        </view>
      </view>
    </view>
    <!-- 商品详情 -->
    <view v-if="activeTab.value == 'details'" class="tab-content">
      <view class="tab-content-body">
        {{ productData?.description }}
      </view>
    </view>
    <!-- 商品特色 -->
    <view v-if="activeTab.value == 'features'" class="tab-content">
      <view class="tab-content-body tab-content-features">
        <view
          v-for="(item, index) in productData?.features"
          class="item-feature">
          <view class="item-left">
            <uni-icons
              type="star"
              size="24"
              style="width: 40px; height: 40px"></uni-icons>
          </view>
          <view class="item-right">
            <view class="title">{{ formatFeature(item, index, 0) }}</view>
            <view class="content">{{ formatFeature(item, index, 1) }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 配料信息 -->
    <view v-if="activeTab.value == 'ingredients'" class="tab-content">
      <view class="tab-content-body tab-content-ingredients">
        {{ productData?.ingredients }}
      </view>
    </view>

    <!-- <view class="line"></view> -->
    <!-- 该商品已有留言 - 屏蔽 不能审核通过 -->
    <commentCheckVue :id="currentId" v-if="false" />
    <!-- 发表留言 - 屏蔽 不能审核通过 -->
    <view class="comment-create" v-if="false">
      <view class="comment-create__title">发表留言</view>
      <uni-easyinput
        type="textarea"
        v-model="comment.content"
        class="comment-create__textarea"
        placeholder="请输入您的使用体验或建议~"
        placeholder-style="color: #c9c9c9;"
        :auto-height="true"
        maxlength="500" />
      <view class="comment-create__rate">
        <text class="comment-create__rate-label">评分：</text>
        <uni-rate
          allow-half
          :value="comment.score"
          :count="5"
          active-color="#ff8a3c"
          inactive-color="#f5f5f5"
          size="24" />
      </view>
      <view class="comment-create__upload">
        <FileUploader
          v-model="comment.images"
          title="上传图片"
          :limit="3"
          @upload-success="handleUploadSuccessComment" />
      </view>
      <!-- 新增提交按钮，完善交互逻辑 -->
      <button class="comment-create__submit" @click="handleSubmitComment">
        提交留言
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import API from "@/api/index.js";
import { completeImgPath } from "@/utils/common.js";
import FileUploader from "./FileUploader.vue";
import commentCheckVue from "./comment-check.vue";

const currentId = ref("");

onLoad((option) => {
  currentId.value = option.id;
});

//格式化特色展示
const formatFeature = (item: string, i: number, index: number) => {
  if (item.includes(":")) {
    return item.split(":")[index] ?? "--";
  }
  if (item.includes("：")) {
    return item.split("：")[index] ?? "--";
  }
  if (index == 0) {
    return `特色${i + 1}`;
  } else {
    return item;
  }
};

const previewImage = (url: string) => {
  let imgsArray = [];
  imgsArray[0] = url;
  uni.previewImage({
    current: 0,
    urls: imgsArray,
  });
};

// 定义产品类型
interface ProductType {
  _id?: string;
  name: string;
  description: string;
  categoryId: string;
  categoryName?: string;
  status: string;
  statusName: string;
  sellingPrice?: number;
  originalPrice?: number;
  mainImage: string;
  detailImages?: string[];
  features?: string[];
  ingredients: string;
  simpleDesc?: string;
  isHot: boolean;
}

//留言
interface CommentType {
  _id?: string;
  userName: string;
  content: string;
  score: number;
  images: string[];
}
//留言
const comment = ref<CommentType>({
  userName: "",
  content: "",
  score: 5,
  images: [],
});

const productData = ref<ProductType>();

const activeDetailIndex = ref(1);
const activeDetailImage = ref();
const detailImage = ref<string[]>([]);

onMounted(async () => {
  await getProductInfoById();
});

//根据id获取商品的全部数据
const getProductInfoById = async () => {
  if (currentId.value) {
    const res = await API.product.getProductInfoByIdApi(currentId.value);
    // console.log("获取单个商品", res);
    if (res.success) {
      productData.value = res.data;
      detailImage.value = productData.value.detailImages;
      activeDetailImage.value = productData.value.detailImages[0];
    }
  }
};

const handleSelectImage = (index) => {
  activeDetailIndex.value = index + 1;
  activeDetailImage.value = detailImage.value[index];
};

interface TabValue {
  text: string;
  value: string;
}
const tabList = ref<TabValue[]>([
  {
    text: "商品详情",
    value: "details",
  },
  {
    text: "商品特色",
    value: "features",
  },
  {
    text: "配料信息",
    value: "ingredients",
  },
]);
const activeTab = ref<TabValue>({
  text: "商品详情",
  value: "details",
});
const switchTab = (tab: TabValue) => {
  activeTab.value = tab;
};

const handleUploadSuccessComment = (urls: string[]) => {
  comment.value.images = urls;
};

//提交留言
const handleSubmitComment = async () => {
  if (currentId.value) {
    if (!comment.value.content) {
      uni.showToast({
        title: "请输入留言",
        icon: "error",
      });
      return;
    }
    //获取下当前的用户信息
    const userData = uni.getStorageSync("userInfo");
    console.log(11111, userData.nickName);
    let data = {
      ...comment.value,
      productId: currentId.value,
      userName: userData.nickName ?? "匿名用户",
    };
    const res = await API.comment.createCommentApi(data);
    if (res.success) {
      uni.showToast({
        title: "留言成功",
        icon: "success",
      });
      comment.value.content = "";
      comment.value.score = 5;
      comment.value.images = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  width: 100vw;
  height: 100vh;

  .no-image-data {
    height: 300px;
    text-align: center;
    line-height: 300px;
  }
  .image-body {
    width: 100%;
    .image-big {
      width: 100vw;
      height: 200px;
      position: relative;
      display: flex;
      justify-content: center;
      .count {
        position: absolute;
        bottom: 10px;
        right: 10px;
        padding: 5px 10px;
        border-radius: 10px;
        background-color: #5d403799;
        color: #fff;
      }
    }
    .image-small-body {
      overflow-x: auto;
      /* 隐藏滚动条但保留滚动功能 */
      -webkit-overflow-scrolling: touch;
      .image-small {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px;
        gap: 16px;
        /* 关键：防止容器被压缩，确保内容能撑开滚动 */
        width: max-content;
        min-width: 100%; /* 确保在内容较少时仍占满宽度 */
        .image-small-item {
          width: 80px;
          height: 80px;
          border-radius: 10px;
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          flex-shrink: 0; /* 防止图片被压缩变形 */
          .image-body {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 10px;
          }
          &.active {
            border: 3px solid #ff8a3c;
          }
        }
      }
    }
  }
  .line {
    height: 2px; /* 线的高度 */
    background-color: #ff8a3c; /* 指定的颜色 */
    opacity: 0.2;
    margin: 0px 10px;
  }
  .detail-middle {
    padding: 10px;
    .top {
      display: flex;
      align-items: center;
      .name {
        font-size: 24px;
        font-weight: 700;
        margin-right: 10px;
        color: #5d4037;
      }
      .status {
        margin-right: 10px;
      }
      .type {
      }
    }
    .middle {
      display: flex;
      align-items: center;
      margin-top: 5px;
      .sellingPrice {
        font-size: 20px;
        font-weight: 700;
        color: #ff8a3c;
        margin-right: 10px;
      }
      .originalPrice {
        font-size: 14px;
        text-decoration: line-through;
        /* 可选：自定义删除线颜色和样式 */
        text-decoration-color: #000000; /* 红色删除线 */
        text-decoration-style: solid; /* 虚线删除线 */
      }
    }
  }
  // 标签滚动容器
  .tab-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    border-bottom: 1px solid #e5e5e5;

    // 隐藏滚动条
    &::-webkit-scrollbar {
      display: none;
    }

    // 标签容器
    .tab-container {
      display: flex;
      padding: 0 16rpx;
      justify-content: center;
      white-space: nowrap;
    }

    // 单个标签
    .tab {
      padding: 24rpx 32rpx;
      font-size: 32rpx;
      color: #6b7280;
      position: relative;
      cursor: pointer;
      transition: color 0.3s ease;

      &:hover {
        color: #ff8a3c;
      }

      // 激活状态
      &.active {
        color: #ff8a3c;
        font-weight: 500;

        &::after {
          content: "";
          position: absolute;
          bottom: -1px;
          left: 0;
          width: 100%;
          height: 5rpx;
          background-color: #ff8a3c;
        }
      }
    }
  }
  .tab-content {
    .tab-content-title {
      color: #5d4037;
      font-size: 24px;
      font-weight: 600px;
      margin-bottom: 10px;
    }
    .tab-content-body {
      padding: 10px 20px;
      font-size: 14px;
      line-height: 2;
      // 关键：保留空格和换行格式
      white-space: pre-wrap;
      // 长文本自动换行
      word-wrap: break-word;
    }
    .tab-content-features {
      .item-feature {
        display: flex;
        align-items: start;
        justify-content: space-between;
        .item-left {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: #ffe4d6;
          line-height: 40px;
          text-align: center;
          margin-right: 10px;
        }
        .item-right {
          width: 90%;
          .title {
            font-size: 18px;
            font-weight: 600px;
            color: #5d4031;
          }
          .content {
            font-size: 14px;
            color: #333;
          }
        }
      }
    }
  }
}

.comment-create {
  width: 100%;
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin: 12px auto;
  max-width: 1200px; /* 限制最大宽度，适配宽屏 */

  // 标题样式：突出层级
  &__title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f5f5f5;
  }

  // 文本输入框样式：优化边框和内边距
  &__textarea {
    width: 100%;
    min-height: 120px;
    padding: 12px 16px;
    background-color: #fafafa;
    border: 1px solid #eee;
    border-radius: 8px;
    font-size: 14px;
    color: #333;
    resize: none;
    transition: border-color 0.3s ease;

    // 聚焦状态：增强视觉反馈
    &:focus {
      border-color: #ff8a3c;
      outline: none;
      box-shadow: 0 0 0 2px rgba(255, 138, 60, 0.1);
    }

    // 适配 uni-easyinput 自带样式，避免冲突
    .uni-easyinput__content {
      background-color: transparent !important;
      border: none !important;
    }
  }

  // 评分区域样式：控制对齐和间距
  &__rate {
    display: flex;
    align-items: center;
    margin: 16px 0;
    gap: 8px;

    // 评分标签样式
    &-label {
      font-size: 14px;
      color: #666;
    }
  }

  // 图片上传区域样式：控制间距
  &__upload {
    margin-bottom: 5px;
    // 适配 FileUploader 组件，调整内部间距
    .file-uploader {
      .upload-btn {
        background-color: #fafafa;
        color: #666;
        border: 1px dashed #eee;
        transition: all 0.3s ease;

        &:hover {
          background-color: #fff;
          border-color: #ff8a3c;
          color: #ff8a3c;
        }
      }

      .image-list {
        margin-top: 12px;
      }
    }
  }

  // 提交按钮样式：突出视觉重点
  &__submit {
    width: 100%;
    height: 48px;
    line-height: 48px;
    background-color: #ff8a3c;
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
    border: none;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #ff7010;
    }

    &:active {
      background-color: #e86300;
    }

    // 禁用状态（可选，根据提交逻辑添加）
    &:disabled {
      background-color: #ffc299;
      cursor: not-allowed;
    }
  }
}
</style>
